﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService.EventHandle
// 文 件 名：	SSTransReceiveBlockFullHandler
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/6/18 23:01:07
//========================================
using SFJDService.TransportHandle;
using System.IO;
using System.Linq;
using System.Threading;

namespace SFJDService.EventHandle
{
    /// <summary>
    /// 文件接收器中的字节块满了之后将字节块存入文件中
    /// </summary>
    internal class SSTransReceiveBlockFullHandler : IEventHandler<SSTransReceiveBlockFullData>
    {
        static ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();

        public void HandleEvent(SSTransReceiveBlockFullData eventData)
        {
            string[] buf1 = eventData.TransInfo.RootPath.Split('\\');
            string lastFolderName = buf1[buf1.Length - 2];//获取文件列表中所有文件的总文件夹名
            string fileRootPath;
            if (eventData.TransInfo.Files.Count == 1)
            {
                fileRootPath = Runtime.thisUser.InPath + "NameSend";//获得用户保存文件的路径
            }
            else
            {
                fileRootPath = Runtime.thisUser.InPath + "NameSend" + "\\" + lastFolderName;//获得用户保存文件的路径 + 总文件件名
            }
            string fileFullPath = fileRootPath + '\\' + eventData.TransInfo.Files[eventData.Block.FileIndex].RelativePath;//获取文件的完整路径
            string[] buf2 = fileFullPath.Split('\\');
            string fileSavePath = fileFullPath.Substring(0, fileFullPath.Count() - buf2.Last().Count());
            if (!Directory.Exists(fileSavePath))
            {
                Directory.CreateDirectory(fileSavePath);
            }
            //创建文件流，然后让文件流来根据路径创建一个文件
            lockSlim.EnterWriteLock();
            FileStream fs = new FileStream(fileFullPath, FileMode.Create);
            //int end = eventData.Block.IndexStart + eventData.Block.Length < eventData.Block.IndexEnd ? eventData.Block.IndexStart + eventData.Block.Length : eventData.Block.IndexEnd;
            int end = eventData.Block.Length < ReceiveBlock.MaxCount ? eventData.Block.IndexStart + eventData.Block.Length : eventData.Block.IndexEnd;
            fs.Write(eventData.Block.Bytes, eventData.Block.IndexStart, end);
            fs.Flush();
            fs.Close();
            Runtime.Printf("存入： " + eventData.Block.IndexStart);
            lockSlim.ExitWriteLock();
        }
    }
}
